package com.cnstrong.webview2.utils

import android.content.Context
import android.os.Build
import android.os.Environment
import java.io.File
import java.io.FileOutputStream

/**
 * @author tgw
 * @date 2022/2/14
 * @describe
 */
object FileUtils {

    const val X5_CORE_CODE = 45738
    const val FILE_SEPARATOR = "/"
    const val X5_FILE = "X5" + FILE_SEPARATOR + "45738_x5.apk"

    /**
     * 复制assets目录下x5/45738_x5.apk 文件
     *
     * @param context   上下文
     * @param mAssetsPath Assets目录的相对路径
     * @param mSavePath   复制文件的保存路径
     * @return void
     */
    fun copyAssetsFiles(context: Context, mAssetsPath: String?, mSavePath: String): String? {
        try {
            val outPath =
                findSdcardPath(context) + FILE_SEPARATOR + mSavePath
            val outFile = File(outPath)
            // 若文件夹不存在，则递归创建父目录
            outFile.parentFile.mkdirs()
            val `is` = context.resources.assets.open(mAssetsPath!!)
            val fos = FileOutputStream(outFile)
            val buffer = ByteArray(1024)
            var byteCount: Int
            // 循环从输入流读取字节
            while (`is`.read(buffer).also { byteCount = it } != -1) {
                // 将读取的输入流写入到输出流
                fos.write(buffer, 0, byteCount)
            }
            // 刷新缓冲区
            fos.flush()
            fos.close()
            `is`.close()
            return outFile.absolutePath
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }


    private fun findSdcardPath(context: Context): String {
        return if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                Environment.getExternalStorageDirectory()
                    .toString() + "/" + context.applicationContext.packageName
            } else {
                context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath + context.applicationContext.packageName
            }
        } else {
            context.cacheDir
                .absolutePath + context.applicationContext.packageName
        }
    }
}